#include "Triangle.h"

Triangle::Triangle(const Vector& _A, const Vector& _B, const Vector& _C)
{
  A=_A;
  B=_B;
  C=_C;
  zNear = 0.0f;
};

Triangle::Triangle(const Triangle& t) { Triangle(t.A,t.B,t.C); };

// TODO: matrix needs to be instantiated thread-safe -> possibly in mesh class
static Matrix m = Matrix();

bool Triangle::Intersect(const Ray& r)
{
  zNear = 0.0f;
  
  // TODO: probably add a safeguard? this equation system is not solvable via my gauss algorithm if r.d==[0,0,0]!
  m.Set(0, A.x-B.x, A.x-C.x, r.d.x, A.x-r.o.x);
  m.Set(1, A.y-B.y, A.y-C.y, r.d.y, A.y-r.o.y);
  m.Set(2, A.z-B.z, A.z-C.z, r.d.z, A.z-r.o.z);
  
  bool solved = m.Solve();
  
  if (solved == true &&                  // system was actually solved
      m.z[0]->m4 >= 0.0f &&              // beta >= 0
      m.z[1]->m4 >= 0.0f &&              // gamma >= 0
      (m.z[0]->m4 + m.z[1]->m4) <= 1.0f) // beta+gamma <= 1
  {
    zNear = m.z[2]->m4;
    return true;
  }
  return false;
};
